import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '@env/environment';
import { SimpleCodegenEditComponent } from './edit/edit.component';

@Component({
  selector: 'app-simple-codegen',
  templateUrl: './codegen.component.html',
})
export class SimpleCodegenComponent implements OnInit {
  selectedRows: STData[] = [];
  stData: STData[] = [];
  datasourceId = "";

  searchSchema: SFSchema = {
    properties: {
      database: {
        type: 'string',
        title: '数据库',
        ui: {
          widget: 'select',
          change: (value:any) => {
            this.datasourceId = value;
            this.http.get(`${environment.simple.ctx}/database/findAllTable/${value}`).subscribe(res=>{
              this.stData = res
            })
          },
          asyncData: () =>{
            return this.http.get(`${environment.simple.ctx}/simpleDatasource`).pipe(map(res=>{
                let databases:any[] = [];
                res.forEach((item:any) => {
                  databases.push({ label: item.name, value: item.id });
                });
                return databases;
            }))
          }
        }
      }
    }
  };
  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'name', type: 'checkbox'  },
    { title: '表名', index: 'name', width: 200},
    { title: '表描述', index: 'comment' },
  ];

  constructor(private http: _HttpClient, private modal: ModalHelper) { }

  ngOnInit() { }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  generate(){
    const names = this.selectedRows.map((row)=>{return row.name})
    this.modal.createStatic(SimpleCodegenEditComponent, { i: {datasourceId: this.datasourceId, names: names} }).subscribe();
  }

}
